package com.hdoit.ares.web.cbase;

import javax.annotation.Resource;

import me.chanjar.weixin.mp.bean.result.WxMpUser;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.selfcommon.enums.AresManageContainer;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.message.WechatLoginModel;
import com.tennetcn.component.intceptor.IWechatAuthedIntceptor;

@Component
public class WechatAuthedIntceptor implements IWechatAuthedIntceptor{
	private ICustomerService customerService;
	
	public ICustomerService getCustomerService() {
		return customerService;
	}
	@Resource
	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	@Override
	public void authed(WechatLoginModel wechatLoginModel,WxMpUser mpUser) {
		if(wechatLoginModel==null){
			return;
		}
		Customer customer=customerService.queryModelByOpenId(wechatLoginModel.getOpenId());
		
		
		//需要考虑的另一种情况就是用户已经在浏览但是并非是通过关注之后进行的浏览
		if(customer==null){
			String openId = mpUser.getOpenId();
			int refereeIdentity=-1;
			customer=customerService.addCustomer(openId, mpUser, refereeIdentity);	
		}else{
			if(StringUtils.isEmpty(customer.getUnionId())){
				customer.setUnionId(mpUser.getUnionId());
				customer.setModelStatus(ModelStatus.update);
				customerService.applyChange(customer);
			}
		}
		
		wechatLoginModel.setUserId(customer.getId());
		
		System.out.println(customer.getId());
		wechatLoginModel.put(AresManageContainer.customer_account_info, customer);
		wechatLoginModel.put(AresManageContainer.customer_account_info_userIdentity, customer.getUserIdentity());
	}
}
